package com.edu.hre.db.sql.pim;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.db.pojo.HreEmpDependents;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.pim.EmpDependentForm;
import com.edu.hre.struts.form.pim.EmpDependentListForm;

public class EmpDependentDAOService implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3394301416150421253L;
	public static final String BEAN_NAME = "empDependentDAOService";
	private BaseService baseService  = null;
	 
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	} 

	public ArrayList<EmpDependentForm> getEmpDependentList(int limit, int offset, int empNumber){

		List<HreEmpDependents> dependents = baseService.getPojos("empNumber", Compare.EQUAL, empNumber, new String[]{"dateCreated"}, new Boolean[]{true}, limit, offset, HreEmpDependents.class);
		ArrayList<EmpDependentForm> result = new ArrayList<EmpDependentForm>();

		if (dependents == null) {
			return result;
		}
		for(HreEmpDependents dep: dependents){
			
			try {

				EmpDependentForm form = new EmpDependentForm();
				form.setId(dep.getId().intValue());
				form.setEdName(CommonUtils.normalizeString(dep.getEdName()));
				form.setEmpNumber(dep.getEmpNumber());
	
				String relType = CommonUtils.normalizeString(dep.getEdRelationshipType());
				if ("0".equals(relType)) {
					form.setEdRelationship("Child");
				} else if ("1".equals(relType)) {
					form.setEdRelationship("Other");
				} else {
					form.setEdRelationship("");
				}
				
				form.setEdDateOfBirth(CommonUtils.dateToString(dep.getEdDateOfBirth()));

				result.add(form);
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
		
		return result;
	}

	public int countEmpDependents(int empNumber){

		int count = baseService.countByColumns(new String[]{"empNumber"}, new int[]{Compare.EQUAL}, new Integer[]{empNumber}, "id", HreEmpDependents.class);
		return count < 0 ? 0 : count;
	}

	public void deleteDependents(EmpDependentListForm form){

		ArrayList<EmpDependentForm> info = (ArrayList<EmpDependentForm>) form.getAllDependents();
		
		for (int i = 0; i < info.size(); i++) {

			try {

				EmpDependentForm dep = info.get(i);
				if (dep.isSelected()) {
					baseService.deleteFirstPojo("id", Compare.EQUAL, (long) dep.getId(), null, null, 0, HreEmpDependents.class);
				}
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
	}
}
